package top.shiyiri.connections;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
import org.junit.Test;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Aunean
 * @date 2022/1/20 11:41
 * @Description C3P0数据库连接池使用
 */
public class C3P0Test {

    //方式一
    @Test
    public void test1() throws PropertyVetoException, SQLException {
        //获取C3P0数据库连接池
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass( "com.mysql.cj.jdbc.Driver" ); //loads the jdbc driver
        cpds.setJdbcUrl( "jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8");
        cpds.setUser("root");
        cpds.setPassword("123456");
        //通过设置相关的参数，对数据库连接池进行管理
        //设置初始时数据库连接池中的连接数
        cpds.setInitialPoolSize(10);

        Connection conn = cpds.getConnection();
        System.out.println(conn);

        //销毁C3P0数据库连接池
        DataSources.destroy(cpds);
    }

    //方式二：
    @Test
    public void test2() {
        //获取C3P0数据库连接池
        ComboPooledDataSource cpds = new ComboPooledDataSource("helloC3P0");

        Connection conn = null;
        try {
            conn = cpds.getConnection();
            System.out.println(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
